import VuiElement from '../../base/element';
import VuiSelectTag from './tag';

/*
 * @Description:
 * @Author: Jevon
 * @Date: 2021-11-25 15:11:46
 */
export default class VuiSelectTagList extends VuiElement {
  constructor(tags) {
    super();
    this.tags = tags || [];
    this._className = {
      container: 'vui-mtselect-tag-list'
    };
  }

  init() {
    this.initContainer();
    this.render();
    return this;
  }

  render() {
    this.tags.forEach(tag => {
      this.append(
        new VuiSelectTag(tag, tag => {
          this.removeTag(tag);
        }).init()
      );
    });
  }

  setTags(tags) {
    this.tags = tags;
    this.render();
  }

  addTag(tag) {
    const index = this.tags.findIndex(t => tag.value === t.value);
    if (index === -1) {
      this.tags.push(tag);
      this.append(
        new VuiSelectTag(tag, tag => {
          this.removeTag(tag);
        }).init()
      );
    }
    console.log(this.tags);
  }

  removeTag(tag) {
    const index = this.tags.findIndex(t => tag.value === t.value);

    if (index !== -1) {
      const elt = this.tags[index].container;
      elt.parentElement.removeChild(elt);
      this.tags.splice(index, 1);
    }
  }
}
